package com.lzq.captchademo.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.lzq.captchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        //1.CREATE
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        System.out.println(lineCaptcha.getCode());
        response.setContentType("image/jpeg");
        response.setHeader("Pragma","No-cache");
        //2.OUTPUT
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captchaProperties.getSession().getKey(),lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            System.out.println(lineCaptcha.getCode());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session) {
        //1.is null
        if(!StringUtils.hasLength(captcha)) return false;
        //2.is correct
        if(!captcha.equals(session.getAttribute(captchaProperties.getSession().getKey()))) return false;
        Date sessionDate = (Date)session.getAttribute(captchaProperties.getSession().getDate());
        Long duration = System.currentTimeMillis()-sessionDate.getTime();
        if(duration>captchaProperties.getValidTime()){
            return false;
        }else{
            return true;
        }
    }
}
